package com.itheima.logdemo.hystrix.callable;

import com.itheima.logdemo.utils.LogBean;
import com.itheima.logdemo.utils.LogUtil;

import java.util.concurrent.Callable;

public final class DelegatingWormholeContextCallable<V> implements Callable<V> {
    private final Callable<V> delegate;
    // 用户信息上下文（根据项目实际情况定义ThreadLocal上下文）
    private LogBean logBean;
    
    public DelegatingWormholeContextCallable(Callable<V> delegate,
                                             LogBean logBean) {
        this.delegate = delegate;
        this.logBean = logBean;
    }
    
    @Override
    public V call() throws Exception {
        LogUtil.removeLocalInstance();
        // 将当前的用户上下文设置进Hystrix线程的TreadLocal中
        LogUtil.setLocalInstance(logBean);
        try {
            return delegate.call();
        } finally {
            // 执行完毕，记得清理ThreadLocal资源
            LogUtil.removeLocalInstance();
        }
    }
    
    public static <V> Callable<V> create(Callable<V> delegate,
                                         LogBean logBean) {
        return new DelegatingWormholeContextCallable<V>(delegate, logBean);
    }
}
